package com.tanhua.server.service;

import com.alibaba.fastjson.JSON;
import com.tanhua.autoconfig.template.HuanXinTemplate;
import com.tanhua.autoconfig.template.SmsTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.dubbo.api.UserApi;
import com.tanhua.dubbo.api.UserLikeApi;
import com.tanhua.model.domain.User;
import com.tanhua.model.enums.UserState;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.server.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserService {

    @Autowired
    private SmsTemplate template;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @DubboReference
    private UserApi userApi;

    @DubboReference
    private UserLikeApi userLikeApi;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    @Autowired
    private UserFreezeService userFreezeService;

    @Autowired
    private AmqpTemplate amqpTemplate;


    /**
     * 发送短信验证码
     * @param phone
     */
    public ErrorResult sendMsg(String phone) {
        //1、随机生成6位数字
        String code = RandomStringUtils.randomNumeric(6);
        //2、调用template对象，发送手机短信
//        template.sendSms(phone,code);
        //3、将验证码存入到redis
        String redisKey = Constants.SMS_CODE + phone;
        //先判断该手机号发送的验证码是否还未失效
        if(Boolean.TRUE.equals(this.redisTemplate.hasKey(redisKey))){
            return ErrorResult.fail();
        }
        redisTemplate.opsForValue().set(redisKey,code, Duration.ofMinutes(5));
        return null;
    }


    /**
     * 验证登录
     * @param phone
     * @param code
     */
    public Map loginVerification(String phone, String code) {
        //2、对验证码进行校验（验证码是否存在，是否和输入的验证码一致）
        if(!checkVerificationCode(phone,code)) {
            //验证码无效
            throw new BusinessException(ErrorResult.loginError());
        }
        //4、通过手机号码查询用户
        User user = userApi.findByMobile(phone);
        boolean isNew = false;
        //5、如果用户不存在，创建用户保存到数据库中
        if(user == null) {
            user = new User();
            user.setMobile(phone);
            user.setPassword(DigestUtils.md5Hex(Constants.INIT_PASSWORD));
            Long userId = userApi.save(user);
            user.setId(userId);
            isNew = true;

            //注册环信用户
            String hxUser = "hx"+user.getId();
            Boolean create = huanXinTemplate.createUser(hxUser, Constants.INIT_PASSWORD);
            if(create) {
                user.setHxUser(hxUser);
                user.setHxPassword(Constants.INIT_PASSWORD);
                userApi.update(user);
            } else {
                log.error("注册环信用户失败~ userId = " + userId);
                throw new BusinessException(ErrorResult.loginError());
            }
        }
        //查看用户是否被冻结
        userFreezeService.checkUserStatus(UserState.LOGIN.getType(),user.getId());

        //构造Map集合
        Map<String, Object> msg = new HashMap<>();
        msg.put("userId", user.getId().toString());
        msg.put("type", "0101");
        msg.put("log_time", new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
        String message = JSON.toJSONString(msg);
        //发送消息
        try {
            amqpTemplate.convertSendAndReceive("tanhua.log.exchange", "log.user",message);
        }catch (Exception e) {
            e.printStackTrace();
        }

        //6、通过JWT生成token(存入id和手机号码)
        Map tokenMap = new HashMap();
        tokenMap.put("id",user.getId());
        tokenMap.put("mobile",phone);
        String token = JwtUtils.getToken(tokenMap);
        //7、构造返回值
        Map retMap = new HashMap();
        retMap.put("token",token);
        retMap.put("isNew",isNew);

        return retMap;
    }

    /**
     * 检查验证码是否有效
     */
    public Boolean checkVerificationCode(String phone, String code) {
        //1、从redis中获取下发的验证码
        String redisCode = redisTemplate.opsForValue().get(Constants.SMS_CODE + phone);
        //2、对验证码进行校验（验证码是否存在，是否和输入的验证码一致）
        if(StringUtils.isEmpty(redisCode) || !redisCode.equals(code)) {
            //验证码无效
            return false;
        }
        //3、删除redis中的验证码
        redisTemplate.delete(Constants.SMS_CODE + phone);
        return true;
    }

    /**
     * 更新手机号
     */
    public void updatePhone(User user) {
        //2、更新数据库中的手机号码
        userApi.updatePhone(user);
    }

    public User findById(Long userId) {
        return userApi.findById(userId);
    }
}
